package org.qiancizhan.Utils;

public class LoadingAnimationUtil {
    // 使用基本ASCII字符，兼容所有终端
    private static final String[] SPINNER_FRAMES = {"-", "\\", "|", "/"};
    private static volatile boolean running = false;
    private static Thread animationThread;

    public static void startLoading(String message) {
        if (running) {
            return;
        }
        running = true;

        animationThread = new Thread(() -> {
            int frameIndex = 0;
            while (running) {
                String frame = SPINNER_FRAMES[frameIndex];
                // 使用System.out代替Terminal，兼容性更好
                System.out.print("\r" + frame + " " + message);

                frameIndex = (frameIndex + 1) % SPINNER_FRAMES.length;
                try {
                    Thread.sleep(200); // 稍微减慢速度，让动画更平滑
                } catch (InterruptedException e) {
                    break;
                }
            }
        });

        animationThread.setDaemon(true);
        animationThread.start();
    }

    public static void stopLoading() {
        running = false;

        // 等待动画线程结束
        if (animationThread != null && animationThread.isAlive()) {
            try {
                animationThread.join(500); // 最多等待500ms
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        // 清空当前行的内容
        System.out.print("\r" + " ".repeat(80) + "\r");
        System.out.flush();
    }
}